package com.whereareyou;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceServletContextListener;
import com.google.inject.servlet.ServletModule;
import com.whereareyou.model.Position;
import com.whereareyou.model.Relationship;
import com.whereareyou.model.User;
import com.whereareyou.servlet.IndexServlet;
import com.whereareyou.servlet.LoginServlet;
import com.whereareyou.servlet.PositionServlet;
import com.whereareyou.servlet.RelationshipServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.servlet.*;
import java.util.Date;

/**
 * Created by 家玮 on 2014/5/19.
 */
public class InitListener extends GuiceServletContextListener{
    final Logger logger = LoggerFactory.getLogger(InitListener.class);
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.print("init 开始");

        User user = new User();
        user.setUsername("liubei");
        user.setPassword("liubei");
        user.setCellPhone("18500643337");
        user.setNickname("中山靖王之后刘备刘玄德");
        user.setPhoto("http://localhost:8080/images/default-user-photo.png");

        User user2 = new User();
        user2.setUsername("zhangfei");
        user2.setPassword("zhangfei");
        user2.setCellPhone("18500643337");
        user2.setNickname("张飞张翼德");
        user2.setPhoto("http://localhost:8080/images/default-user-photo.png");
        Util.save(user,user2);

        Relationship relationship = new Relationship();
        relationship.setDateCreated(new Date());
        relationship.setUser1(user.getId());
        relationship.setUser2(user2.getId());
        relationship.setUser1Nickname("大哥");
        relationship.setUser2Nickname("三弟");

        Util.save(relationship);

        Position position1 = new Position();
        position1.setUser(user2);
        position1.setLat(33.0);
        position1.setLng(33.0);
        position1.setDateCreated(new Date());

        Util.save(position1);
        super.contextInitialized(servletContextEvent);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }

    @Override
    protected Injector getInjector() {
        return Guice.createInjector(new Modules(),new ServletModule(){
            @Override
            protected void configureServlets() {
                serve("/position/*","/position").with(PositionServlet.class);
                serve("/relationship/*","/relationship").with(RelationshipServlet.class);
                serve("/login").with(LoginServlet.class);
                serve("/").with(IndexServlet.class);
//                filter("/*").through(MyFilter.class);
            }
        });
    }
}